﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.U2D.Animation;

public class Board : MonoBehaviour
{
    public int Width = 10;
    public int Height = 20;


    public Dictionary<Vector2, Cell> Cells = new Dictionary<Vector2, Cell>();

    public void CreateCells()
    {
        if (Cells == null)
        {
            Cells = new Dictionary<Vector2, Cell>();
        }
        else
        {
            Cells.Clear();
        }
    }

    // Start is called before the first frame update
    void Start()
    {
    }

    public void Init()
    {
        foreach (Transform child in transform)
        {
            Cell cell = child.GetComponent<Cell>();
            Cells.Add(cell.positon, cell);
        }
    }

    /// <summary>
    /// 根据给定的位置，返回相应的Cell（格子），当给定的位置超出棋盘范围时，范围 null
    /// </summary>
    /// <param name="cellPosition">要获取的cell的坐标</param>
    /// <returns>指定的cell</returns>
    public Cell GetCell(Vector2 cellPosition)
    {
       
        if (cellPosition.x >= 0 && cellPosition.x < GameManager.Instance.board.Width && cellPosition.y >= 0 &&
            cellPosition.y < GameManager.Instance.board.Height)
        {
            
            return Cells[cellPosition];
        }
        else
        {
            return null;
        }
    }

    public void AddCell(Cell cellObject)
    {
        Cells.Add(cellObject.positon,cellObject);
    }

    public void DoDestory()
    {
        int y = 0;
        while ( y < Height)
        {
            if (IsFullLine(y))
            {
                Debug.Log("满了");
                DestroyLine(y);
                FallInLineDonw(y);
                y = 0;
                continue;
            }
            y++;
        }
    }

    bool IsFullLine(int y) //指定行，满没满
    {
        for (int x = 0; x < Width; x++)
        {
            if (Cells[new Vector2(x, y)].state != CellState.Fixed)
            {
                return false; //没有满
            }
        }

        return true; //满了
    }

    void DestroyLine(int y) //删除这一指定行
    {
        for (int x = 0; x < Width; x++)
        {
            Cells[new Vector2(x, y)].state = CellState.None;
        }
    }

    void FallInLineDonw(int yLine) //删除行以后，上面的行自然下落
    {
       // Debug.Log("FallInLineDonw的Y轴" + yLine);
       // Debug.Log(Cells[new Vector2(0, yLine + 1)].state.ToString());
        for (int y = yLine; y < Height-1; y++)
        {
            for (int x = 0; x < Width; x++)
            {
                Cells[new Vector2(x, y)].state = Cells[new Vector2(x, y + 1)].state;
            }
        }
    }

    void Update()
    {
    }
}